import alertFill from "@/assets/image/icons/alert-fill.svg";
import { StyledAgree, StyledCancel } from "@/components/button";
import { StyledCardBorder, StyledTextAlign } from "@/components/common-styled";
import CustomModal from "@/components/customModal";
import {
  CustomSubTitle,
  CustomTitle,
  RenderLabel,
} from "@/components/customTitle";
import { ProForm, ProFormSlider } from "@ant-design/pro-components";
import { Descriptions, Divider, Flex, Form, message, Space } from "antd";
import React, { useEffect, useRef, useState } from "react";
import styled from "styled-components";
import { history } from "umi";
import CardSelection from "./components/Vehicle";
// import MyDatePicker from "./components/MyDatePicker";
import useParkStore from "@/store/parkStore";
import dayjs from "dayjs";
import DateTips from "./components/DateTips";
import DualCalendar from "./components/MydatePicker1";
import TermsCheck from "./components/terms-check";
import "./index.less";

const StyledBorderCard = styled("div")`
width: 100%
height: 101px;
padding: 24px 24px 24px 24px;
gap: 24px;
border-radius: 12px 0px 0px 0px;
background: #F7F5F1;
`;

const CustomLabel = styled.span`
  font-family: Roboto;
  font-size: 14px;
  font-weight: 400;
  line-height: 21px;
  color: #696767;
`;

const CustomContent = styled.span`
  font-family: Roboto;
  font-size: 16px;
  font-weight: 400;
  line-height: 24px;
  color: #202020;
`;
const CustomContentPrice = styled(CustomContent)`
  font-weight: 700;
`;

export const targetTime = new Date().getTime() + 15 * 60 * 1000;
export const formatTime = (currentTime: any) => {
  const minutes = Math.floor(currentTime / 1000 / 60);
  const remainingSeconds = Math.floor(currentTime / 1000) % 60;
  return `${minutes}:${remainingSeconds < 10 ? "0" : ""}${remainingSeconds}`;
};
const DailyPark: React.FC = () => {
  const [form] = Form.useForm();
  const formRef = useRef(form);

  const { price, setPymPrice, setStartDate, setPeriod } = useParkStore();
  const [parkingPeriod, setParkingPeriod] = useState(1); // 初始值为 1
  const [originalTime, setOriginalTime] = useState<string>("");
  const [totalCost, setTotalCost] = useState(
    `HK$${Number(price) * parkingPeriod}`
  );

  // const deadline = 1000 * 30; // Moment is also OK
  // 取消cancel booking
  const [isModalCancel, setIsModalCancel] = useState(false);
  // 是否需要提交状态
  const [isNeedSubmit, setIsNeedSubmit] = useState(false);
  const handleSliderChange = (value: number) => {
    setParkingPeriod(value); // 更新状态为 slider 的值
    setPeriod(value);
  };

  const onFinish = async (values: any) => {
    console.log("Form values=====", values);
    history.push("/payment/monthly/payment-info");
    // 处理提交逻辑
    setIsNeedSubmit(true);
    // const licenseNumberKeys = Object.keys(values).filter(
    //   (key) => key.includes("licenseNumber") && values[key] === "123456"
    // );
    // if (licenseNumberKeys.length > 0) {
    //   console.log("Form values2:", values);
    //   setisModalCancelFailed(true);
    // } else {
    //   setIsModalCancel(true);
    // }
  };
  //错误验证拦截
  const onFinishFailed = () => {
    message.error({ content: "please check required field" });
    const firstInvalidField = document.querySelector(
      ".ant-form-item-has-error"
    );
    if (firstInvalidField) {
      firstInvalidField.scrollIntoView({ behavior: "smooth" });
    }
  };

  const handleClickNext = () => {
    history.push("/register");
    // setIsModalCancel(true);
  };

  // // Submit Modal   submit 提交
  const handleOkCancel = async () => {
    //处理提交数据
    history.back();
  };

  const handleCancelBtn = () => {
    setIsModalCancel(true);
  };

  const handleCancelBooking = () => {
    setIsModalCancel(false);
  };

  const handleDateSelect = (date: any) => {
    setOriginalTime(dayjs(date).format("YYYY-MM-DD"));

    console.log("Selected date:", date);
  };
  // const clockEnd = () => {
  //   console.log("倒计时结束");
  // };

  console.log(price, "price");
  useEffect(() => {
    setTotalCost(`HK$${Number(price) * parkingPeriod}`);
    setPymPrice(String(Number(price) * parkingPeriod));
    setStartDate(originalTime);
  }, [price, parkingPeriod, originalTime]);
  return (
    <div className="daily_content">
      <CustomTitle className="title">Create Daily Booking</CustomTitle>
      <StyledCardBorder>
        <ProForm
          initialValues={{}}
          form={form}
          onFinish={onFinish}
          onFinishFailed={onFinishFailed}
          submitter={{
            render: () => (
              <StyledTextAlign>
                <Space size="large">
                  <StyledCancel type="default" onClick={handleCancelBtn}>
                    Cancel
                  </StyledCancel>
                  <StyledAgree
                    onClick={
                      isNeedSubmit
                        ? handleClickNext
                        : () => formRef.current?.submit()
                    }
                    type="default"
                  >
                    {isNeedSubmit ? "Submit" : "Next"}
                  </StyledAgree>
                </Space>
              </StyledTextAlign>
            ),
          }}
        >
          <CardSelection />

          <Flex justify="space-between">
            <CustomSubTitle className="second_title">
              Fill in Parking Information
            </CustomSubTitle>
            {/* <StyledClock>Time left for submit booking 14:59</StyledClock> */}
          </Flex>
          {/* <MyDatePicker /> */}
          {RenderLabel("Choose Parking Entry Date")}
          <DualCalendar onDateSelect={handleDateSelect} />
          <DateTips />
          <ProFormSlider
            name="slider"
            label={RenderLabel("Choose Parking Period")}
            min={1} // 最小值
            max={14} // 最大值
            tooltip
            className="slider"
            fieldProps={{
              defaultValue: 1, // 默认值
              tooltipVisible: true, // 默认显示 tooltip
              // placement: 'bottom',
              tooltip: {
                placement: "bottom",
              },

              onChange: handleSliderChange, // 当 slider 值变化时更新状态
              //  tooltipFormatter={(value) => `${value} days`}
            }}

            // 格式化 tooltip 的内容
          />
          <StyledBorderCard>
            <Descriptions layout="vertical" column={4}>
              <Descriptions.Item label={<CustomLabel>Entry Date</CustomLabel>}>
                <CustomContent>{originalTime}</CustomContent>
              </Descriptions.Item>
              <Descriptions.Item
                label={<CustomLabel>Parking period</CustomLabel>}
              >
                <CustomContent>{parkingPeriod}</CustomContent>
              </Descriptions.Item>
              <Descriptions.Item
                label={<CustomLabel>Payment Amount</CustomLabel>}
              >
                <CustomContentPrice>{totalCost}</CustomContentPrice>
              </Descriptions.Item>
            </Descriptions>
          </StyledBorderCard>
          <Divider plain></Divider>

          <TermsCheck />
        </ProForm>
      </StyledCardBorder>
      <CustomModal
        icon={alertFill}
        title=" Cancel Booking?"
        content="The associated data will be permanently erased."
        onOk={handleOkCancel}
        onCancel={handleCancelBooking}
        isModalOpen={isModalCancel}
        btnLeftText="Cancel"
        btnRightText="Cancel Booking"
        btnRightBgColor="#C02020"
      />
      {/* submitted Failed modal */}
    </div>
  );
};

export default DailyPark;
